package mx.edu.itesm.tps.proyecto.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import mx.edu.itesm.tps.proyecto.pojo.User;

//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.webflow.action.FormAction;

public class UserDao extends FormAction implements ProjectEventDao {

    private SimpleJdbcTemplate simpleJdbcTemplate;
    private SimpleJdbcInsert insertUser;


    public void setDataSource(DataSource dataSource) {
        this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
        this.insertUser = new SimpleJdbcInsert(dataSource).withTableName("Users");
    }

    public List getUsers() {
        return simpleJdbcTemplate.queryForList("SELECT * FROM users", new Object[]{});
    }

    public List getProfs() {
        return simpleJdbcTemplate.queryForList("SELECT * FROM users WHERE type = ?", new Object[]{User.TYPE_PROF});
    }

    public User getUserById(String id) {
        return getById(id);
    }

    private User getById(String id) {

        try {
            return simpleJdbcTemplate.queryForObject("SELECT * FROM users WHERE user = ?", new UserMapper(), id);
        } catch (EmptyResultDataAccessException erdae) {
            User u = new User();
            u.setUserName(id);

            if ((id.startsWith("A") || (id.startsWith("a")))) {
                u.setType(User.TYPE_ALUM);
            } else {
                u.setType(User.TYPE_PROF);
            }

            add(u);


            return u;
        }
    }

    public void add(User user) {
        Map<String, Object> parameters = new HashMap<String, Object>(User.class.getDeclaredFields().length);
        parameters.put("user", user.getUserName());
        parameters.put("type", user.getType());

        insertUser.execute(parameters);

    }

    private class UserMapper implements ParameterizedRowMapper<User> {

        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setUserName(rs.getString("user"));
            user.setType(rs.getInt("type"));
            return user;
        }
    }
}
